﻿var Forms = Forms || {};
Forms.Pagination = (function () {
    // private fields and functions
    var form = null;
    var fieldState = {};

    // Hook into the click event of the pagination control and to set the page number and submit the form
    function initialize() {
        $('.pagination ul li a').click(function (e) {
            form = $(this).closest('form');

            var page = getPageFrom($(this).attr('href'));
            if (page === null) return false;

            setPageNumber(page);

            var input = $('input[type="submit"]', form)[0];
            input.click();

            e.preventDefault();
            return false;
        });
    }

    // Set page number from clicked link
    function setPageNumber(page) {
        var pageNumber = parseInt(page);

        $('input[type="hidden"][name="Xii.Page"]', form).attr('value', pageNumber);
    }

    function getPageFrom(url) {
        var match = RegExp('[?&]xii\.page=([^&]*)').exec(url);
        return match ? decodeURIComponent(match[1].replace(/\+/g, ' ')) : null;
    }

    function log(message) {
        if (window.console) console.log(message);
    }

    return { // public methods
        initialize: initialize
    };
} ());